package com.zhonglian.education.view.my.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.text.format.Formatter;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.tbruyelle.rxpermissions2.RxPermissions;
import com.zhonglian.education.BuildConfig;
import com.zhonglian.education.EduApplication;
import com.zhonglian.education.MainActivity;
import com.zhonglian.education.R;
import com.zhonglian.education.base.AppManager;
import com.zhonglian.education.base.BaseActivity;
import com.zhonglian.education.common.dialogs.DialogConfirmUtil;
import com.zhonglian.education.common.download.DownloadCircleDialog;
import com.zhonglian.education.common.download.DownloadUtils;
import com.zhonglian.education.common.download.FileUtils;
import com.zhonglian.education.common.download.progress.body.ProgressInfo;
import com.zhonglian.education.config.AppConfig;
import com.zhonglian.education.utils.ClearCacheUtils;
import com.zhonglian.education.utils.LogUtil;
import com.zhonglian.education.utils.NoDoubleClickUtil;
import com.zhonglian.education.utils.SPUtils;
import com.zhonglian.education.utils.ToastUtils;
import com.zhonglian.education.view.login.activity.LoginActivity;
import com.zhonglian.education.view.my.presenter.MyPresenter;
import com.zhonglian.education.view.notify.viewer.IPublicViewer;

import io.reactivex.functions.Consumer;

/**
 * Created : Yx
 * Time : 2019/3/29 18:24
 * Describe :设置
 */
public class SettingActivity extends BaseActivity {

    private TextView tv_left, tv_title;
    private RelativeLayout setting_rl_version, setting_rl_cache;
    private TextView setting_code, setting_tv_caches, setting_loginout;
    private DownloadCircleDialog dialog;
    private RxPermissions rxPermissions;
    private String versionPath = "";

    @Override
    public int initLayout() {
        return R.layout.activity_setting;
    }

    @Override
    public void initView() {
        tv_left = (TextView) findViewById(R.id.tv_left);
        tv_title = (TextView) findViewById(R.id.tv_title);
        tv_title.setText("设置");
        tv_left.setOnClickListener(clicks);
        setting_rl_version = findViewById(R.id.setting_rl_version);//版本信息
        setting_code = findViewById(R.id.setting_code);//版本号
        setting_rl_cache = findViewById(R.id.setting_rl_cache);//清理缓存
        setting_tv_caches = findViewById(R.id.setting_tv_caches);//缓存显示
        setting_loginout = findViewById(R.id.setting_loginout);//退出登录
        String vn = BuildConfig.VERSION_NAME;
        setting_code.setText(vn);
        try {
            String caches = ClearCacheUtils.getTotalCacheSize(getApplicationContext());
            setting_tv_caches.setText(caches);
        } catch (Exception e) {
            LogUtil.iYx("--获取缓存失败--" + e.getMessage());
        }
        setting_rl_version.setOnClickListener(clicks);
        setting_rl_cache.setOnClickListener(clicks);
        setting_loginout.setOnClickListener(clicks);

        //检测新版本
        MyPresenter.getInstance().myVersion(BuildConfig.VERSION_CODE + "", new IPublicViewer() {
            @Override
            public void onSuccessPublic(String str) {
                versionPath = str;
            }

            @Override
            public void onFail(String str) {

            }
        });

    }

    private View.OnClickListener clicks = (v) -> {
        switch (v.getId()) {
            case R.id.tv_left:
                finish();
                break;
            case R.id.setting_rl_version://版本信息
                if (NoDoubleClickUtil.isFastClick()) return;
                //DialogCardTipsUtil.showCardTips(SettingActivity.this, 0, null, "当前版本:" + vn, false);
                if (TextUtils.isEmpty(versionPath)) {
                    ToastUtils.showToastApplication("已是最新版本!");
                    return;
                }
                DialogConfirmUtil.showConfirmDefault(SettingActivity.this, "检测到新版本", "是否下载?", new DialogConfirmUtil.OnConfirmCallback() {
                    @SuppressLint("CheckResult")
                    @Override
                    public void onSuccess(String str) {
                        rxPermissions = new RxPermissions(SettingActivity.this);
                        dialog = new DownloadCircleDialog(SettingActivity.this);
                        //是否有读写权限
                        rxPermissions.request(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE).subscribe(new Consumer<Boolean>() {
                            @Override
                            public void accept(Boolean aBoolean) throws Exception {
                                if (aBoolean) {//授权成功
                                    //FileUtil.createFolder();
                                    downloadApk(SettingActivity.this, versionPath);
                                } else {
                                    ToastUtils.showToastApplication("请添加读写权限！");
                                }
                            }
                        });
                    }

                    @Override
                    public void onFail(String str) {

                    }
                });

                break;
            case R.id.setting_rl_cache://清理缓存
                try {
                    ClearCacheUtils.clearAllCache(getApplicationContext());
                    setting_tv_caches.setText("0K");
                } catch (Exception e) {
                    LogUtil.iYx("--清理缓存失败--" + e.getMessage());
                }
                break;
            case R.id.setting_loginout://退出登录
                DialogConfirmUtil.showConfirmDefault(this, "确认退出应用吗?", "", new DialogConfirmUtil.OnConfirmCallback() {
                    @Override
                    public void onSuccess(String str) {
                        //AppManager.getAppManager().AppExit();
                        SPUtils.remove(AppConfig.USER_ID);
                        SPUtils.remove(AppConfig.USER_PWD);
                        EduApplication.getInstance().setJpushTag("");
                        startActivity(new Intent(SettingActivity.this, LoginActivity.class));
                        finish();
                        AppManager.getAppManager().finishActivity(MainActivity.class);
                    }

                    @Override
                    public void onFail(String str) {

                    }
                });
                break;
        }
    };


    /**
     * 下载
     *
     * @param context
     * @param down_url
     */
    public void downloadApk(final Activity context, String down_url) {
        dialog.show();
        LogUtil.iYx("存储地址：" + FileUtils.mFile());///storage/emulated/0/DCIM/
        DownloadUtils.getInstance().download(down_url, FileUtils.mFile(), "jbj.apk", new DownloadUtils.OnDownloadListener() {
            @Override
            public void onDownloadSuccess() {
                dialog.dismiss();
                LogUtil.iYx("恭喜你下载成功，开始安装！==" + FileUtils.mFile() + "jbj.apk");
                ToastUtils.showToastApplication("下载成功！");
                String successDownloadApkPath = FileUtils.mFile() + "jbj.apk";
                installApkO(SettingActivity.this, successDownloadApkPath);
            }

            @Override
            public void onDownloading(ProgressInfo progressInfo) {
                dialog.setProgress(progressInfo.getPercent());
                boolean finish = progressInfo.isFinish();
                if (!finish) {
                    long speed = progressInfo.getSpeed();
                    dialog.setMsg("(" + (speed > 0 ? Formatter.formatFileSize(context, speed) : speed) + "/s)正在下载...");
                } else {
                    dialog.setMsg("下载完成！");
                }

            }

            @Override
            public void onDownloadFailed() {
                dialog.dismiss();
                ToastUtils.showToastApplication("下载失败！");
            }
        });

    }


    /**
     * 兼容8.0安装位置来源的权限
     */
    String downloadApkPaths = "";

    @SuppressLint("CheckResult")
    private void installApkO(Context context, String downloadApkPath) {
        downloadApkPaths = downloadApkPath;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            //是否有安装位置来源的权限
            rxPermissions.request(Manifest.permission.REQUEST_INSTALL_PACKAGES).subscribe(new Consumer<Boolean>() {
                @Override
                public void accept(Boolean aBoolean) throws Exception {
                    if (aBoolean) {//授权成功
                        //FileUtil.createFolder();
                        LogUtil.iYx("安装地址：" + downloadApkPath);
                        FileUtils.installApk(context, downloadApkPaths);
                    } else {
                        ToastUtils.showToastApplication("请打开安装未知来源应用权限!");
                        toInstallPermissionSettingIntent();
                    }
                }
            });

        } else {
            FileUtils.installApk(context, downloadApkPaths);
        }
    }


    private void toInstallPermissionSettingIntent() {//打开安装未知来源的设置界面
        Uri packageURI = Uri.parse("package:" + getPackageName());
        Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI);
        startActivityForResult(intent, 100);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                if (getPackageManager().canRequestPackageInstalls()) {//再次判断有没有授予
                    FileUtils.installApk(SettingActivity.this, downloadApkPaths);
                }
            }
        }

    }


}
